package com.westvalley.service.api.nc;

import java.util.Map;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.westvalley.common.kit.StringKit;
import com.westvalley.common.result.JsonResult;
import com.westvalley.http.HttpXmlClient;
import com.westvalley.syn.address.prop.AddressProp;

public abstract class NcService {
	protected String url;
	private JsonType jsonType;
	
	protected NcService(String key,JsonType jsonType){
		this.url = AddressProp.me().getPropValue(key);
		this.jsonType = jsonType;
	}
	
	/**
	 * 执行接口
	 * @param params 接口参数集合
	 * @return
	 */
	protected String executeInterface(Map<String,Object> params){
		Map<String,String> map = Maps.newHashMap();
		for(Entry<String, Object> entry : params.entrySet()){
			map.put(entry.getKey(), StringKit.null2o(entry.getValue()));
		}
		return HttpXmlClient.post(this.url, map);
	}
	
	/**
	 * 获取结果
	 * @return
	 */
	public JsonResult getJsonResult(){
		JsonResult jsonResult = com.westvalley.common.result.JsonResult.me("未知错误");
		try{
			Map<String,Object> params = initParams();
			String interfaceData = executeInterface(params);
			JSONObject ob = JSON.parseObject(interfaceData);;
			if(ob!=null){
				String status = ob.getString("status");
				if(StringKit.equals(status, "0")){
					if(JsonType.arr.equals(jsonType))
						jsonResult = com.westvalley.common.result.JsonResult.me(ob.getJSONArray("data"));
					else if(JsonType.obj.equals(jsonType))
						jsonResult = com.westvalley.common.result.JsonResult.me(ob);
				}else{
					throw new RuntimeException(ob.getString("message"));
				}
			}
		}catch (Exception e) {
			jsonResult = com.westvalley.common.result.JsonResult.me(e);
		}
		return jsonResult;
	}
	
	
	/**
	 * 初始化接口需求传入参数
	 * @param params
	 */
	protected abstract Map<String,Object> initParams();
	
	/**
	 * 接口数据格式
	 * @author 莫双
	 *
	 */
	public enum JsonType{
		obj,arr
	}
}
